const BACKEND_ENDPOINT = "/editor/spec"


async function getItem(url) {
  const res = await fetch(url, {
    method: "GET"
  })
  return await res.text()
}


function setItem(url, str) {
  (async () => {
    await fetch(url, {
      method: "PUT",
      body: str
    })
  })()


}

export const updateSpec = (ori) => (...args) => {
  let [spec] = args
  ori(...args)
  saveContentToBackendEndpoint(spec)
}

export default function (system) {
  // setTimeout runs on the next tick
  setTimeout(() => {
    getItem(BACKEND_ENDPOINT).then((yml) => {
        system.specActions.updateSpec(yml, "net-storage")
      }
    )

  }, 0)
  return {
    statePlugins: {
      spec: {
        wrapActions: {
          updateSpec
        }
      }
    }
  }
}

function saveContentToBackendEndpoint(str) {
  return setItem(BACKEND_ENDPOINT, str)
}
